<template>
    <div class="box">
        <div class="header">
            <input type="text" placeholder="请输入内容" v-model="contents">
            <button @click="pub">发布</button>
        </div>
        <ul>
            <li v-for="(item, index) in comments" :key="item.id">
                <span>{{ item.content }}</span>
                <div>
                    <span class="del" @click="delByIndex(index)">删除</span>
                </div>
            </li>
        </ul>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
const contents = ref('')
const comments = ref([])
// let object;

// 删除(index下标方法)
const delByIndex = (index) => {
    if (confirm(`确认删除${comments.value[index].content}吗`)) {
        // splice会改变原数组
        comments.value.splice(index, 1)
    }
}

// 发布
const pub = () => {
    if (contents.value.trim() === '') {
        return
    }
    comments.value.push({ id: Date.now(), content: contents.value })
    // let key = Date.now()
    // localStorage.setItem(  contents.value,contents.value )
    // let newValue = JSON.parse(localStorage.getItem(object))
    localStorage.setItem( 'key', JSON.stringify(contents.value))
    // 清空输入框
    contents.value = ''
}

watch(comments, (newValue) => {
    localStorage.setItem( 'key', JSON.stringify(newValue))
},{deep: true})

onMounted(() => {
    let results = JSON.parse(localStorage.getItem('key') ? localStorage.getItem('key') : '[]')
    comments.value = results
})

// onMounted(() => {
//     comments.value.push(JSON.parse(localStorage.getItem('obj') ? localStorage.getItem('obj') : '[]'))
// })

// localStorage.setItem() 
// localStorage.getItem()
// JSON.stringify(对象/数组): 将其序列化为json字符串
// JSON.parse(json字符串)：将json字符串转化为js对象
// let results = JSON.parse(localStorage.getItem('obj') ? localStorage.getItem('obj') : '[]')

</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}
.box {
    width: 300px;
    margin: 50px auto;
}

.box .header {
    display: flex;
}

button {
    flex-grow: 1;
}



ul li {
    display: flex;
    justify-content: space-between;
}

ul li .del {
    color: blue;
    cursor: pointer;
    padding: 0 2px;
}
</style>